/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 8.3下午1.c
> Author:
> Mail: 
> Created Time: Sat 03 Aug 2024 08:53:23 AM PDT
***************************************************/
//用父子进程分别统计一个文本文件中字符：
//父进程统计其中数字字符个数
//子进程统计字母字符个数
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>

int main(int argc,const char* argv[])
{
	int fd[2] = {0};
	pid_t pid = 0;
	int res = 0;

	res =pipe(fd); //创建管道
	if(res == -1)
	{
		perror("pipe");
	}
	pid = fork();
	if(pid == 0)
	{
		int fd1  = open("./music/temp.txt",O_RDWR);
		if(fd1 <= 0)
		{  
			perror("open");
			exit(-1);
		}
		char buf[20] = {0};
		int count = 0;
		close(fd[1]);
		while((res =  read(fd1,buf,1))> 0)
		{
			
			if(isalpha(buf[0]))
			{
				count++;
			}
			memset(buf,0,1);
		}
		printf("%d\n",count);
		sleep(5);
		close(fd1);
		exit(-1);
	}
	else if(pid < 0)
	{
		printf("fork error\n");
	}




	int fd1 = open("./music/temp.txt",O_RDWR);
	if(fd1 == -1)
	{
		perror("open");
	}
	char buf[20] ={0};
	int count = 0;
	close(fd[0]);
	while((res = read(fd1,buf,1))>0)
	{
		if(isdigit(buf[0]))
		{
			count++;
		}
		memset(buf,0,1);
	}
	printf("%d\n",count);
	close(fd1);
	wait(NULL);
	return 0;
}
